<template>
  <view class="customer-container">
    <view class="header-section">
      <u-navbar
        :border-bottom="false"
        :is-back="false"
        title-color="#fff"
        title=" "
        :background="nav_background"
      >
        <view class="search-box">
          <u-search
            height="72"
            placeholder-color="#777777"
            bg-color="#F5F5F5"
            :show-action="false"
            :clearabled="true"
            color="#555555"
            @search="searchConfirm"
            placeholder="请输入客户名称或手机号查询..."
            @clear="searchConfirm"
            v-model="search_form.keyword"
          ></u-search>
        </view>
      </u-navbar>
      <view class="tabs-section">
        <u-tabs-swiper
          ref="tabs"
          font-size="26"
          :current="tabs_current"
          :list="tabs_list"
          @change="tabsChange"
          :is-scroll="false"
          inactive-color="#62738E"
          :bar-style="{
            borderRadius: '6rpx',
            height: '6rpx',
            width: '32rpx',
            backgroundColor: '#FB5904',
          }"
          :active-item-style="{
            color: '#FB5904',
            fontSize: '32rpx',
            fontWeight: 'bold',
          }"
        ></u-tabs-swiper>

        <!-- 筛选栏 -->
        <view class="filter-container">
          <view class="filter-left">
            <view class="filter-item" @click="openSel('account_status_show')">
              <text class="filter-text">{{ account_status_name }}</text>
              <u-icon name="arrow-down-fill" size="24" color="#999999"></u-icon>
            </view>
            <view class="filter-item" @click="goPage('/pagesT/shop/selShop')">
              <text class="filter-text">{{ shop_name }}</text>
              <u-icon name="arrow-down-fill" size="24" color="#999999"></u-icon>
            </view>
            <view class="filter-item" @click="goPage('/pagesT/staff/selStaff')">
              <text class="filter-text">{{ salesName }}</text>
              <u-icon name="arrow-down-fill" size="24" color="#999999"></u-icon>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 列表信息和重置按钮 -->
    <view class="list-summary">
      <view class="summary-text">共{{ total }}条</view>
      <view class="reset-btn" @click="clearValue()">
        <u-icon name="reload" size="24" color="#FB5904"></u-icon>
        <text>重置</text>
      </view>
    </view>

    <scroll-view
      class="customer-list"
      scroll-y="true"
      @refresherrefresh="refresherrefresh"
      :refresher-enabled="true"
      :refresher-triggered="refresher_triggered"
      @scrolltolower="scrolltolower"
    >
      <view
        class="customer-card"
        v-for="(item, index) in customer_list"
        :key="index"
        @click="goPage(`/pagesT/customer/CustomerDetail?id=${item.id}`)"
      >
        <view class="card-header">
          <view class="customer-info">
            <view class="customer-type" v-if="item.customerType">{{
              item.customerType
            }}</view>
            <view class="customer-name">{{ item.name }}</view>
            <view
              class="status-tag"
              :class="item.enableStatus === 5 ? 'active' : 'inactive'"
            >
              {{ item.enableStatus === 5 ? "已启用" : "已禁用" }}
            </view>
          </view>
        </view>

        <view class="card-content">
          <view class="info-row">
            <view class="info-card">
              <view class="info-label">联系人</view>
              <view class="info-value">{{
                item.contact[0].name || "暂无"
              }}</view>
            </view>
            <view class="info-card">
              <view class="info-label">联系电话</view>
              <view
                class="info-value phone-value"
                @click.stop="callPhone(item.mobile)"
                >{{ item.mobile }}</view
              >
            </view>
          </view>

          <view class="info-row">
            <view class="info-card">
              <view class="info-label">业务员</view>
              <view class="info-value">{{
                item.salesManName || "未指派"
              }}</view>
            </view>
            <view class="info-card">
              <view class="info-label">创建时间</view>
              <view class="info-value">{{
                $u.timeFormat(item.createTime, "yyyy-mm-dd")
              }}</view>
            </view>
          </view>
        </view>

        <view class="card-footer">
          <view
            class="action-btn"
            v-if="item.status === 2 && item.enableStatus === 5"
            @click.stop="orderAdd(item)"
          >
            <u-icon name="file-text" size="28" color="#FB5904"></u-icon>
            <text>开单</text>
          </view>
          <view
            class="action-btn"
            v-else-if="item.status === 0"
            @click.stop="goPage('/pagesT/customer/AddCustomer?id=' + item.id)"
          >
            <u-icon name="edit-pen" size="28" color="#FB5904"></u-icon>
            <text>完善资料</text>
          </view>
          <view
            class="action-btn approval-btn"
            v-else-if="item.status === 1"
            @click.stop="openModel('确定要审核通过该客户吗？', '审核', item)"
          >
            <u-icon name="checkmark-circle" size="28" color="#FB5904"></u-icon>
            <text>审核通过</text>
          </view>
        </view>
      </view>
      <view v-if="!customer_list.length" class="empty-view"
        ><u-empty text="暂无客户数据" mode="list"></u-empty
      ></view>
      <u-loadmore v-if="customer_list.length" :status="load_status" />
    </scroll-view>
    <addBtn
      v-if="$accessCheck($Access.CustomerListAddCustomer)"
      url="/pagesT/customer/AddCustomer"
    ></addBtn>

    <!-- 弹窗部分保持不变 -->
    <u-popup v-model="search_show" mode="right">
      <view class="search-pop">
        <uniStatusBar></uniStatusBar>
        <view class="form-view" style="padding-top: 45px">
          <u-form label-width="160rpx" label-position="left">
            <u-form-item label="下单时间">
              <view class="clearfix form-val" @click="openSel('month_show')">
                <text class="float_left ellipsis">{{
                  search_form.time_value ? search_form.time_name : "请选择"
                }}</text>
                <view
                  class="float_right"
                  @click.stop="clearValue('time_value')"
                >
                  <u-icon
                    :name="
                      !search_form.time_value
                        ? 'arrow-right'
                        : 'close-circle-fill'
                    "
                    size="28"
                    color="#999999"
                  ></u-icon>
                </view>
              </view>
            </u-form-item>
          </u-form>
        </view>
        <view class="search-btn">
          <view class="btn-li btn-reset" @click="clearValue()">重置</view>
          <view class="btn-li btn-submit" @click="searchConfirm">确定</view>
        </view>
      </view>
    </u-popup>
    <u-select
      @confirm="fromChange"
      v-model="from_show"
      :list="order_from"
    ></u-select>
    <u-select
      @confirm="accountStatusChange"
      v-model="account_status_show"
      :list="account_status"
    ></u-select>
    <SelDeparment
      v-model="show_department"
      @confirm="departmentConfirm"
      @cancel="departmentCancel"
    />
    <RegionSel
      v-model="region_show"
      @confirm="regionConfirm"
      @cancel="regionCancel"
    />
    <u-modal
      v-model="model_show"
      :show-cancel-button="true"
      :content="model_content"
      @confirm="modelConfirm"
      @cancel="modelCancel"
    ></u-modal>
    <u-select
      v-model="month_show"
      :list="tabs_list1"
      @confirm="confirm"
    ></u-select>
    <!-- 底部tabbar -->
    <Tabbar v-model="tabbar_current"></Tabbar>
  </view>
</template>

<script>
import RegionSel from "@/components/region/RegionSel.vue";
import SelDeparment from "@/components/SelDepartment.vue";
import uniStatusBar from "../../components/uni-status-bar.vue";
export default {
  components: {
    RegionSel,
    SelDeparment,
    uniStatusBar,
  },
  data() {
    return {
      refresher_triggered: false, //设置当前下拉刷新状态，true 表示下拉刷新已经被触发，false 表示下拉刷新未被触发
      tabbar_current: 1,
      nav_background: {
        backgroundColor: "#FB5904",
      },
      model_tag: "",
      model_show: false,
      model_content: "",
      from_show: false,
      show_department: false,
      region_show: false,
      search_show: false,
      customer_list: [],
      load_status: "nomore",
      page: 1,
      pageSize: 10,
      total: 0,
      tabs_current: 0,
      status: 2,
      salesName: "业务员",
      staffData: "",
      region_name: "",
      shopData: "",
      shop_name: "所属店铺",
      department_name: "",
      sourceName: "注册来源",
      search_form: {
        keyword: "",
        type: "",
        enableStatus: 5,
        shopId: "", // 商铺Id
        content: "",
        salesManId: "",
        source: "",
        tag: "",
        time_name: "",
        time_value: "",
      },
      handel_data: {}, // 需要操作的客户
      order_from: [
        {
          label: "ios",
          value: 1,
        },
        {
          label: "安卓",
          value: 2,
        },
        {
          label: "微信小程序",
          value: 3,
        },
        {
          label: "后台创建",
          value: 4,
        },
        {
          label: "H5页面",
          value: 5,
        },
        {
          label: "pc页面",
          value: 6,
        },
        {
          label: "字节跳动小程序",
          value: 8,
        },
      ],
      account_status: [
        {
          value: 5,
          label: "已启用",
        },
        {
          value: 4,
          label: "已禁用",
        },
      ],
      tabs_list: [
        {
          value: 2,
          name: "已审核",
        },
        {
          value: 1,
          name: "待审核",
        },
        {
          value: 0,
          name: "待完善",
        },
      ],
      account_status_show: false,
      account_status_name: "账户状态",
      tabs_list1: [
        {
          label: "当月",
          value: 0,
        },
        {
          label: "当日",
          value: 1,
        },
      ],
      month_show: false,
    };
  },
  watch: {
    staffData(val) {
      if (val) {
        this.search_form.salesManId = val.id;
        this.salesName = val.staffName;
        this.page = 1;
        this.getAllCustomer();
      }
    },
    shopData(val) {
      if (val) {
        this.search_form.shopId = val.id;
        this.shop_name = val.name;
        this.page = 1;
        this.getAllCustomer();
      }
    },
  },
  onLoad() {
    this.getAllCustomer();
  },
  methods: {
    //滚动到底部,上拉加载
    scrolltolower() {
      if (this.total / this.pageSize > this.page) {
        this.page += 1;
        this.getAllCustomer();
      }
    },
    //客户审核
    updateCustomerCheckStatus() {
      this.$u.api
        .updateCustomerCheckStatus({
          id: this.handel_data.id,
          status: 2,
        })
        .then((res) => {
          this.getAllCustomer();
          this.$u.toast("审核成功");
        });
    },
    //开单
    orderAdd(item) {
      const obj = {
        shopId: item.shopId,
        userCenterId: item.userCenterId,
        customerId: item.id,
        customerName: item.name,
      };
      this.goPage("/pages/order/OrderAdd?customer=" + JSON.stringify(obj));
    },
    // 状态切换
    tabsChange(index) {
      this.tabs_current = index;
      this.status = this.tabs_list[index].value;
      this.page = 1;
      this.getAllCustomer();
    },
    // 获取所有客户数据
    getAllCustomer() {
      if (!this.$accessCheck(this.$Access.CustomerListGetCustomerInfo)) {
        this.$u.toast("抱歉，您没有权限");
        return;
      }
      this.load_status = "loading";
      this.$u.api
        .getAllCustomer({
          page: this.page,
          pageSize: this.pageSize,
          status: this.status,
          ...this.search_form,
        })
        .then((res) => {
          // 设置当前下拉刷新状态为false
          this.refresher_triggered = false;
          if (this.page === 1) {
            this.customer_list = res.data;
          } else {
            this.customer_list = this.customer_list.concat(res.data);
          }
          this.total = res.pageTotal;
          this.load_status = this.$utils.loadStatus(
            this.page,
            this.pageSize,
            this.total
          );
        })
        .catch((err) => {
          // 设置当前下拉刷新状态为false
          this.refresher_triggered = false;
        });
    },
    statusChange(row) {
      this.search_form.enableStatus = row.value;
    },
    regionConfirm(val) {
      this.search_form.provinceCode = val[0].value;
      this.search_form.cityCode = val[1].value;
      this.search_form.districtCode = val[2].value;
      let name = "";
      val.forEach((item) => {
        name += item.label;
      });
      this.region_name = name;
    },
    regionCancel(val) {
      this.region_show = false;
    },
    departmentConfirm(val) {
      this.search_form.departmentId = val[val.length - 1].value;
      this.department_name = val[val.length - 1].label;
      this.search_form.salesManId = "";
      this.salesName = "";
    },
    departmentCancel(val) {
      this.show_department = false;
    },
    // 来源筛选
    fromChange(e) {
      this.search_form.source = e[0].value;
      this.sourceName = e[0].label;
      this.page = 1;
      this.getAllCustomer();
    },
    openSel(key) {
      this[key] = true;
    },
    searchConfirm() {
      this.search_show = false;
      this.page = 1;
      this.getAllCustomer();
    },
    clearValue(params) {
      if (!params) {
        this.sourceName = "注册来源";
        this.shop_name = "所属店铺";
        this.salesName = "业务员";
        this.account_status_name = "账户状态";
        this.search_form = {
          keyword: "",
          type: "",
          enableStatus: 5,
          shopId: "", // 商铺Id
          content: "",
          salesManId: "",
          source: "",
          tag: "",
          time_name: "",
          time_value: "",
        };
        this.searchConfirm();
      } else {
        if (Array.isArray(params)) {
          params.forEach((item) => {
            this.search_form[item] = "";
          });
          this.region_name = "";
        } else {
          this.search_form[params] = "";
        }
      }
    },
    // 打开提示框
    openModel(content, tag, row) {
      this.model_content = content;
      this.model_show = true;
      this.model_tag = tag;
      this.handel_data = row;
    },
    // 审核
    modelConfirm() {
      switch (this.model_tag) {
        case "审核":
          this.updateCustomerCheckStatus();
          break;
        case "拒绝":
          this.revokeAudit();
          break;
      }
    },
    modelCancel() {},
    accountStatusChange(e) {
      this.search_form.enableStatus = e[0].value;
      this.account_status_name = e[0].label;
      this.page = 1;
      this.getAllCustomer();
    },
    confirm(val) {
      this.search_form.time_value = val[0].value;
      this.search_form.time_name = val[0].label;
    },
    callPhone(mobile) {
      uni.makePhoneCall({
        phoneNumber: mobile,
      });
    },
    // 下拉刷新
    refresherrefresh() {
      this.refresher_triggered = true;
      this.page = 1;
      this.getAllCustomer();
    },
  },
};
</script>

<style lang="scss" scoped>
.customer-container {
  background-color: #f8f8f8;
  min-height: 100vh;
}

.header-section {
  background: linear-gradient(180deg, #fb5904, #fb7a37, #ff8f59);
  padding-bottom: 0;
  border-bottom-left-radius: 30rpx;
  border-bottom-right-radius: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

  .search-box {
    margin: 10rpx 20rpx;
    width: 710rpx;
    height: 72rpx;
  }

  .tabs-section {
    width: 100%;
    background-color: #ffffff;
    border-radius: 20rpx 20rpx 0 0;
    padding: 10rpx 0 0;
    overflow: hidden;

    /* 筛选容器 */
    .filter-container {
      padding: 16rpx 30rpx;
      background-color: #ffffff;
      border-top: 1px solid #f5f5f5;
      margin-top: 10rpx;

      .filter-left {
        display: flex;
        justify-content: space-around;
        flex-wrap: wrap;

        .filter-item {
          display: flex;
          align-items: center;
          margin-right: 40rpx;

          .filter-text {
            font-size: 26rpx;
            color: #333333;
            margin-right: 8rpx;
          }
        }
      }
    }
  }
}

/* 列表信息 */
.list-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #ffffff;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.05);

  .summary-text {
    font-size: 26rpx;
    color: #666666;
  }

  .reset-btn {
    display: flex;
    align-items: center;
    padding: 10rpx 20rpx;
    background-color: rgba(251, 89, 4, 0.1);
    border-radius: 8rpx;

    text {
      font-size: 26rpx;
      color: #fb5904;
      margin-left: 8rpx;
    }
  }
}

/* 客户列表 */
.customer-list {
  height: calc(100vh - 370rpx);
  padding: 0 20rpx 20rpx;
  box-sizing: border-box;

  .customer-card {
    width: 100%;
    margin-bottom: 24rpx;
    background-color: #ffffff;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
    overflow: hidden;

    .card-header {
      padding: 24rpx;
      border-bottom: 1px solid #f5f5f5;

      .customer-info {
        display: flex;
        align-items: center;

        .customer-type {
          display: inline-block;
          padding: 6rpx 16rpx;
          background: #fb5904;
          color: #ffffff;
          font-size: 24rpx;
          border-radius: 6rpx;
          margin-right: 16rpx;
        }

        .customer-name {
          font-size: 32rpx;
          font-weight: 600;
          color: #333333;
          flex: 1;
        }

        .status-tag {
          padding: 6rpx 16rpx;
          border-radius: 6rpx;
          font-size: 24rpx;

          &.active {
            background-color: rgba(140, 193, 82, 0.1);
            color: #8cc152;
          }

          &.inactive {
            background-color: rgba(237, 85, 101, 0.1);
            color: #ed5565;
          }
        }
      }
    }

    .card-content {
      padding: 24rpx;

      .info-row {
        display: flex;
        margin-bottom: 20rpx;

        &:last-child {
          margin-bottom: 0;
        }

        .info-card {
          flex: 1;
          background-color: #f9f9f9;
          border-radius: 12rpx;
          padding: 16rpx;
          margin-right: 16rpx;

          &:last-child {
            margin-right: 0;
          }

          .info-label {
            font-size: 24rpx;
            color: #999999;
            margin-bottom: 8rpx;
          }

          .info-value {
            font-size: 28rpx;
            color: #333333;
            font-weight: 500;

            &.phone-value {
              color: #fb5904;
            }
          }
        }
      }
    }

    .card-footer {
      display: flex;
      justify-content: flex-end;
      padding: 20rpx 24rpx;
      border-top: 1px solid #f5f5f5;

      .action-btn {
        display: flex;
        align-items: center;
        padding: 10rpx 24rpx;
        border-radius: 8rpx;
        background-color: rgba(251, 89, 4, 0.1);

        text {
          font-size: 26rpx;
          color: #fb5904;
          margin-left: 8rpx;
        }
      }
    }
  }
}

.empty-view {
  padding-top: 100rpx;
}

// 保留原有弹窗样式
.search-pop {
  background-color: #ffffff;
  height: 100%;

  .form-view {
    padding: 30rpx;
  }

  .form-val {
    height: 80rpx;
    line-height: 80rpx;
    border-bottom: 1px solid #f0f0f0;
  }

  .search-btn {
    position: absolute;
    bottom: 40rpx;
    left: 0;
    width: 100%;
    display: flex;

    .btn-li {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      font-size: 30rpx;

      &:first-child {
        background: #f0f0f0;
        color: #666666;
      }

      &:last-child {
        background: #fb5904;
        color: #ffffff;
      }
    }
  }
}
.search-btn {
  .btn-reset {
    color: #fb5904 !important;
  }
  .btn-submit {
    background-color: #fb5904 !important;
  }
}
</style>
